package com.jinbei.filter;

import com.jinbei.common.annotation.AuthorAnnotation;

import com.jinbei.common.contants.Contants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zflu
 * 拦截器 将注解中的日志和权限 存入 request
 * Created by lucky on 2018/7/10.
 */
@Component
public class LoggerInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        HandlerMethod handler = null;
        if (o instanceof HandlerMethod){
            handler = (HandlerMethod) o;
        }
        if(handler != null){
            Method method = handler.getMethod();
            //拦截注解日志
            AuthorAnnotation annotation = method.getAnnotation(AuthorAnnotation.class);
            if(annotation == null){
                return true;
            }
            String logs = annotation.logs();
            boolean flag = annotation.flag();
            if(StringUtils.isNotBlank(logs)){
                httpServletRequest.setAttribute(Contants.LOGS,logs);
            }
            httpServletRequest.setAttribute(Contants.FLAG,flag);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
